package com.wxsm.wechat.util;

import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with Yang Huan
 * Date: 2017/3/2
 * Time: 11:34
 */
public class IPUtil {

    public static String getServerIp() {
        HttpServletRequest request = ActionUtil.getRequest();
        String remoteAddress = request.getRemoteAddr();
        String headerXForwardedFor = request.getHeader("X-Forwarded-For");
        return headerXForwardedFor == null ? remoteAddress : headerXForwardedFor.split(",")[0];
    }

    public static String getClientIp() {
        HttpServletRequest request = ActionUtil.getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("http_client_ip");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        // 如果是多级代理，那么取第一个ip为客户ip
        if (!StringUtils.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个不为 unknown 的才为真实IP
            String[] ips = ip.split(",");
            for (String i : ips) {
                i = i.trim();
                if (!StringUtils.isEmpty(i) && !"unknown".equalsIgnoreCase(i)) {
                    ip = i;
                    break;
                }
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.indexOf(":") > 0) {
            ip = request.getLocalAddr();
        }
        return ip;
    }
}
